package com.jhws.business.comm.api;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.jhws.common.base.bo.Global;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.jhws.business.comm.bo.TblBuildingDimBo;
import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.business.device.bo.UserDevice;
import com.jhws.util.GetId;
import com.jhws.core.db.BaseDao;
import com.jhws.common.base.bo.BaseJson;
import com.jhws.business.comm.service.CommService;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.util.AuthMangager;
import com.jhws.util.security.Des3;
import com.jhws.util.LogHelper;

/**
 * 小区查询
 *
 * @author xiaokek
 * @since 2015年12月27日 上午10:34:33
 */
@Controller
@RequestMapping({ "/commctrl", "/commInfo" })
public class CommApi{
	private BaseDao dao = new BaseDao();

	@Resource
	protected ITblCommDimService ICommService;
	
	@Resource
	private CommService service;

	@Resource
	private ITblBuildingDimService IBuildingService;

	@RequestMapping({ "queryComm.x", "getCommOfUser" })
	@ResponseBody
	public JsonRespData queryComm(String username) {
		LogHelper.getLogger().debug(username);
		return new JsonRespData("getCommOfUser", 1, service.query(username));
	}

	@RequestMapping("getUnitsInfo")
	@ResponseBody
	public Object getUnitsInfo(String commCode,Integer type) throws Exception{

		String where = "where 1=1 and comm_code = '" + commCode + "'";

		if(type != null){
            if(Global.BUILDING_NORMAL == type || Global.BUILDING_VILLA == type)
                where += " and building_type = '"+type+"'";
            else{
                return new JsonRespData("",-1,"无法识别的楼栋类型");
            }
		}

		List<TblBuildingDimBo> list = IBuildingService.findTblBuildingDimByWhere(where);
		return new JsonRespData("",1,list);
	}

	@RequestMapping({ "getCityByComm.x", "getCityByComm" })
	public void getCityByComm(String city, HttpServletResponse response) throws Exception {
		/* 演示虚拟小区，代表test属性小区 */
		if (city.equals("演示")) {
			getCityByCommTest(response);
			return;
		}
		String where = " where comm_state='deploy' and ";
		PrintWriter out = null;
		if (!city.equals("")) {
			where = where + "comm_city like '%" + city + "%' ";
		}
		try {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			// 这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			List<TblCommDimBo> tblCommDimBos = ICommService.findTblCommDimByWhere(where);
			if (tblCommDimBos.size() > 0) {
				out.append(JSON.toJSONString(new BaseJson<List<TblCommDimBo>>(tblCommDimBos, "outdoor", 1)));
			} else {
				out.append(JSON.toJSONString(new BaseJson<String>("没有可选择小区", "outdoor", -1)));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.append(JSON.toJSONString(new BaseJson<String>(e.toString(), "outdoor", -1)));
			e.printStackTrace();
		}
	}

	// 小区鉴权
	@RequestMapping({ "getCityByCommAuthentication.x", "getCityByCommAuthentication" })
	public void getCityByCommAuthentication(HttpServletResponse response, String password, String commCode) {
		PrintWriter out = null;
		try {
			response.setHeader("Content-type", "textml;charset=UTF-8");
			// 这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			if (!StringUtils.isEmpty(commCode)) {
				if (commCode.length() == 12 || commCode.length() == 4) {
					String comm;
					if (commCode.length() == 12) {
						comm = commCode.substring(0, 4);
					} else {
						comm = commCode;
					}
					String commPassword = dao.j().queryForObject(
							"select comm_password from tbl_comm_dim  where comm_code = ? ", new Object[] { comm },
							String.class);

					if (password.equals(commPassword)) {
						String uid = GetId.randomID();
						String token = Des3.encode(commCode + ";" + password + ";" + uid);
						AuthMangager.instance().addToken(commCode, token);
						out.append(JSON.toJSONString(new BaseJson<String>(uid, "outdoor", 1)));
					} else {
						out.append(JSON.toJSONString(new BaseJson<String>("鉴权失败", "outdoor", -1)));
					}
				} else {
					String commPassword = dao.j().queryForObject(
							"select password from tbl_sipacount_dim  where username = ? ", new Object[] { commCode },
							String.class);
					if (password.equals(commPassword)) {
						String uid = GetId.randomID();
						String token = Des3.encode(commCode + ";" + password + ";" + uid);
						AuthMangager.instance().addToken(commCode, token);
						out.append(JSON.toJSONString(new BaseJson<String>(uid, "outdoor", 1)));
					} else {
						out.append(JSON.toJSONString(new BaseJson<String>("鉴权失败", "", -1)));
					}
				}
			} else {
				out.append(JSON.toJSONString(new BaseJson<String>("鉴权失败", "outdoor", -1)));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.append(JSON.toJSONString(new BaseJson<String>(e.toString(), "outdoor", -1)));
			e.printStackTrace();
		}
	}

	// 返回所有测试小区
	@RequestMapping({ "getCityByCommTest.x", "getCityByCommTest" })
	public void getCityByCommTest(HttpServletResponse response) {
		String where = " where ";
		PrintWriter out = null;
		where = where + "comm_state='test' ";
		try {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			// 这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			List<TblCommDimBo> tblCommDimBos = ICommService.findTblCommDimByWhere(where);
			if (tblCommDimBos.size() > 0) {
				out.append(JSON.toJSONString(new BaseJson<List<TblCommDimBo>>(tblCommDimBos, "outdoor", 1)));
			} else {
				out.append(JSON.toJSONString(new BaseJson<String>("没有可选择小区", "outdoor", -1)));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.append(JSON.toJSONString(new BaseJson<String>(e.toString(), "outdoor", -1)));
			e.printStackTrace();
		}
	}

	@RequestMapping("getManagerDevices")
	@ResponseBody
	public JsonRespData getManagerDevices(String commCode) {
		List<UserDevice> userDevices = new ArrayList<>();
		int mengagerNum = dao.j().queryForObject("select manage_dev_number from tbl_comm_dim where comm_code = ? ",
				new Object[] { commCode }, Integer.class);
		UserDevice userDevice;
		for (int i = 1; i <= mengagerNum; i++) {
			userDevice = new UserDevice();
			userDevice.setAccounts(commCode+"0000000"+i);
			userDevice.setDisplayName("管理机-"+i);
			userDevices.add(userDevice);
		}
		return new JsonRespData("getManagerDevices", 1, userDevices);
	}
}
